package com.tryon.controller;

import com.tryon.entity.GarmentLibrary;
import com.tryon.entity.PersonLibrary;
import com.tryon.entity.TryonHistory;
import com.tryon.repository.GarmentLibraryRepository;
import com.tryon.repository.PersonLibraryRepository;
import com.tryon.repository.TryonHistoryRepository;
import com.tryon.service.OssService;
import com.tryon.service.TongYiService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 虚拟试衣控制器
 * @generatedBy AI-CodeGen
 * @lastModified 2025-10-27
 */
@Slf4j
@RestController
@RequestMapping("/tryon")
@CrossOrigin
public class TryOnController {
    
    @Autowired
    private OssService ossService;
    
    @Autowired
    private TongYiService tongYiService;
    
    @Autowired
    private GarmentLibraryRepository garmentLibraryRepository;
    
    @Autowired
    private PersonLibraryRepository personLibraryRepository;
    
    @Autowired
    private TryonHistoryRepository tryonHistoryRepository;
    
    /**
     * 上传用户照片（支持保存到形象库）
     */
    @PostMapping("/upload/person")
    public ResponseEntity<Map<String, Object>> uploadPersonImage(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "userId", required = false) Long userId,
            @RequestParam(value = "personName", required = false) String personName,
            @RequestParam(value = "remarks", required = false) String remarks,
            @RequestParam(value = "saveToLibrary", required = false, defaultValue = "false") Boolean saveToLibrary) {
        log.info("========== 接收到上传用户照片请求 ==========");
        log.info("文件名: {}", file.getOriginalFilename());
        log.info("文件大小: {} bytes ({} KB)", file.getSize(), file.getSize() / 1024);
        log.info("文件类型: {}", file.getContentType());
        log.info("保存到库: {}", saveToLibrary);
        log.info("是否为空: {}", file.isEmpty());
        
        try {
            // 验证文件不为空
            if (file.isEmpty()) {
                log.error("❌ 上传的文件为空");
                Map<String, Object> response = new HashMap<>();
                response.put("message", "文件为空，请选择有效的图片文件");
                return ResponseEntity.badRequest().body(response);
            }
            
            String url = ossService.uploadFile(file, "syj/person");
            log.info("✅ 用户照片上传成功，URL: {}", url);
            
            // 如果需要保存到形象库
            Long personId = null;
            if (saveToLibrary && userId != null) {
                PersonLibrary person = new PersonLibrary();
                person.setUserId(userId);
                person.setImageUrl(url);
                person.setPersonName(personName);
                person.setRemarks(remarks);
                
                PersonLibrary saved = personLibraryRepository.save(person);
                personId = saved.getId();
                log.info("✅ 形象信息已保存到数据库，ID: {}", personId);
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("url", url);
            response.put("personId", personId);
            response.put("message", "上传成功");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("❌ 上传用户照片失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("message", "上传失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 上传服装图片（支持服装类型、备注和保存到衣橱）
     */
    @PostMapping("/upload/garment")
    public ResponseEntity<Map<String, Object>> uploadGarmentImage(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "garmentType", required = false) String garmentType,
            @RequestParam(value = "userId", required = false) Long userId,
            @RequestParam(value = "garmentName", required = false) String garmentName,
            @RequestParam(value = "remarks", required = false) String remarks,
            @RequestParam(value = "saveToLibrary", required = false, defaultValue = "false") Boolean saveToLibrary) {
        log.info("========== 接收到上传服装图片请求 ==========");
        log.info("文件名: {}", file.getOriginalFilename());
        log.info("文件大小: {} bytes ({} KB)", file.getSize(), file.getSize() / 1024);
        log.info("文件类型: {}", file.getContentType());
        log.info("服装类型: {}, 保存到库: {}", garmentType, saveToLibrary);
        log.info("是否为空: {}", file.isEmpty());
        
        try {
            // 验证文件不为空
            if (file.isEmpty()) {
                log.error("❌ 上传的文件为空");
                Map<String, Object> response = new HashMap<>();
                response.put("message", "文件为空，请选择有效的图片文件");
                return ResponseEntity.badRequest().body(response);
            }
            
            String url = ossService.uploadFile(file, "syj/garment");
            log.info("✅ 服装图片上传成功，URL: {}", url);
            
            // 如果需要保存到衣橱
            Long garmentId = null;
            if (saveToLibrary && userId != null && garmentType != null && !garmentType.isEmpty()) {
                GarmentLibrary garment = new GarmentLibrary();
                garment.setUserId(userId);
                garment.setGarmentType(garmentType);
                garment.setImageUrl(url);
                garment.setGarmentName(garmentName);
                garment.setRemarks(remarks);
                
                GarmentLibrary saved = garmentLibraryRepository.save(garment);
                garmentId = saved.getId();
                log.info("✅ 服装信息已保存到数据库，ID: {}, 类型: {}", garmentId, garmentType);
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("url", url);
            response.put("garmentId", garmentId);
            response.put("message", "上传成功");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("❌ 上传服装图片失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("message", "上传失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 执行虚拟试衣（支持多件服装）
     */
    @PostMapping("/process")
    public ResponseEntity<Map<String, Object>> processTryOn(@RequestBody TryOnRequest request) {
        log.info("========== 接收到虚拟试衣请求 ==========");
        log.info("📷 用户照片URL: {}", request.getPersonImageUrl());
        
        // 验证输入参数
        if (request.getPersonImageUrl() == null || request.getPersonImageUrl().isEmpty()) {
            log.error("❌ 用户照片URL为空");
            Map<String, Object> response = new HashMap<>();
            response.put("message", "用户照片URL不能为空");
            return ResponseEntity.badRequest().body(response);
        }
        
        // 处理多件服装或单件服装（向后兼容）
        List<GarmentItem> garments = request.getGarments();
        
        // 如果没有 garments，尝试从旧格式构建
        if (garments == null || garments.isEmpty()) {
            if (request.getGarmentImageUrl() != null && !request.getGarmentImageUrl().isEmpty()) {
                log.info("👔 使用旧格式单件服装");
                GarmentItem singleGarment = new GarmentItem();
                singleGarment.setImageUrl(request.getGarmentImageUrl());
                singleGarment.setType(request.getGarmentType());
                singleGarment.setName(request.getGarmentName());
                singleGarment.setGarmentId(request.getGarmentId());
                garments = new ArrayList<>();
                garments.add(singleGarment);
            } else {
                log.error("❌ 没有提供服装信息");
                Map<String, Object> response = new HashMap<>();
                response.put("message", "请至少上传一件服装");
                return ResponseEntity.badRequest().body(response);
            }
        }
        
        log.info("👔 服装数量: {}", garments.size());
        for (int i = 0; i < garments.size(); i++) {
            GarmentItem g = garments.get(i);
            log.info("  服装 {}: type={}, name={}, url={}", i+1, g.getType(), g.getName(), g.getImageUrl());
        }
        
        try {
            String resultUrl;
            
            // 如果只有一件服装，使用原有方法
            if (garments.size() == 1) {
                GarmentItem garment = garments.get(0);
                log.info("使用单件服装处理方法");
                resultUrl = tongYiService.processTryOn(
                    request.getPersonImageUrl(),
                    garment.getImageUrl(),
                    garment.getType(),
                    garment.getName()
                );
            } else {
                // 多件服装：目前先用第一件处理（后续可以实现真正的多件处理）
                log.info("⚠️ 多件服装模式：当前使用第一件处理，后续将实现真正的多件搭配");
                GarmentItem firstGarment = garments.get(0);
                resultUrl = tongYiService.processTryOn(
                    request.getPersonImageUrl(),
                    firstGarment.getImageUrl(),
                    firstGarment.getType(),
                    firstGarment.getName()
                );
            }
            
            // 验证返回结果
            if (resultUrl == null || resultUrl.isEmpty()) {
                log.error("❌ AI服务返回的图片URL为空");
                Map<String, Object> response = new HashMap<>();
                response.put("message", "AI处理失败：未返回结果图片");
                return ResponseEntity.status(500).body(response);
            }
            
            log.info("✅ 虚拟试衣处理成功");
            log.info("🖼️  结果图片URL: {}", resultUrl);
            
            // 如果提供了用户ID，自动保存到历史记录
            Long historyId = null;
            if (request.getUserId() != null) {
                try {
                    TryonHistory history = new TryonHistory();
                    history.setUserId(request.getUserId());
                    history.setPersonImageUrl(request.getPersonImageUrl());
                    history.setResultImageUrl(resultUrl);
                    
                    // 保存第一件服装信息（兼容旧字段）
                    GarmentItem firstGarment = garments.get(0);
                    history.setGarmentImageUrl(firstGarment.getImageUrl());
                    history.setGarmentType(firstGarment.getType());
                    history.setGarmentId(firstGarment.getGarmentId());
                    
                    // 保存多件服装ID列表（如果有）
                    if (garments.size() > 1) {
                        String garmentIds = garments.stream()
                            .map(g -> g.getGarmentId() != null ? g.getGarmentId().toString() : "")
                            .filter(s -> !s.isEmpty())
                            .collect(Collectors.joining(","));
                        history.setGarmentIds(garmentIds);
                        log.info("💾 保存多件服装IDs: {}", garmentIds);
                    }
                    
                    TryonHistory saved = tryonHistoryRepository.save(history);
                    historyId = saved.getId();
                    log.info("✅ 试衣历史已自动保存，ID: {}", historyId);
                } catch (Exception e) {
                    log.warn("⚠️ 保存试衣历史失败，但不影响试衣结果: {}", e.getMessage());
                }
            }
            
            // 构建响应
            Map<String, Object> response = new HashMap<>();
            response.put("resultUrl", resultUrl);
            response.put("historyId", historyId);
            response.put("garmentCount", garments.size());
            response.put("message", "试衣成功");
            response.put("success", true);
            
            log.info("📤 返回给前端: {}", response);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("❌ 虚拟试衣处理失败", e);
            log.error("错误详情: {}", e.getMessage());
            
            Map<String, Object> response = new HashMap<>();
            response.put("message", "处理失败: " + e.getMessage());
            response.put("success", false);
            
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 保存试衣历史
     */
    @PostMapping("/history/save")
    public ResponseEntity<Map<String, Object>> saveTryonHistory(@RequestBody SaveHistoryRequest request) {
        log.info("========== 保存试衣历史 ==========");
        
        try {
            TryonHistory history = new TryonHistory();
            history.setUserId(request.getUserId());
            history.setPersonImageUrl(request.getPersonImageUrl());
            history.setGarmentId(request.getGarmentId());
            history.setGarmentImageUrl(request.getGarmentImageUrl());
            history.setResultImageUrl(request.getResultImageUrl());
            history.setGarmentType(request.getGarmentType());
            
            TryonHistory saved = tryonHistoryRepository.save(history);
            log.info("✅ 试衣历史已保存，ID: {}", saved.getId());
            
            Map<String, Object> response = new HashMap<>();
            response.put("id", saved.getId());
            response.put("message", "保存成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("❌ 保存试衣历史失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("message", "保存失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 直接创建服装记录（图片已上传）
     */
    @PostMapping("/garments/create")
    public ResponseEntity<Map<String, Object>> createGarment(@RequestBody GarmentLibrary garment) {
        log.info("========== 创建服装记录 ==========");
        
        try {
            GarmentLibrary saved = garmentLibraryRepository.save(garment);
            log.info("✅ 服装创建成功，ID: {}", saved.getId());
            
            Map<String, Object> response = new HashMap<>();
            response.put("garment", saved);
            response.put("message", "创建成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("❌ 创建服装失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("message", "创建失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 直接创建形象记录（图片已上传）
     */
    @PostMapping("/persons/create")
    public ResponseEntity<Map<String, Object>> createPerson(@RequestBody PersonLibrary person) {
        log.info("========== 创建形象记录 ==========");
        
        try {
            PersonLibrary saved = personLibraryRepository.save(person);
            log.info("✅ 形象创建成功，ID: {}", saved.getId());
            
            Map<String, Object> response = new HashMap<>();
            response.put("person", saved);
            response.put("message", "创建成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("❌ 创建形象失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("message", "创建失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 查询用户的服装库
     */
    @GetMapping("/garments")
    public ResponseEntity<Map<String, Object>> getUserGarments(
            @RequestParam("userId") Long userId,
            @RequestParam(value = "garmentType", required = false) String garmentType) {
        log.info("========== 查询用户服装库 ==========");
        log.info("用户ID: {}, 类型: {}", userId, garmentType);
        
        try {
            List<GarmentLibrary> garments;
            if (garmentType != null && !garmentType.isEmpty()) {
                garments = garmentLibraryRepository.findByUserIdAndGarmentTypeAndIsDeleted(userId, garmentType, 0);
            } else {
                garments = garmentLibraryRepository.findByUserIdAndIsDeleted(userId, 0);
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("garments", garments);
            response.put("total", garments.size());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("❌ 查询服装库失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 查询用户的试衣历史
     */
    @GetMapping("/history")
    public ResponseEntity<Map<String, Object>> getUserHistory(@RequestParam("userId") Long userId) {
        log.info("========== 查询用户试衣历史 ==========");
        log.info("用户ID: {}", userId);
        
        try {
            List<TryonHistory> history = tryonHistoryRepository.findByUserIdAndIsDeletedOrderByCreatedAtDesc(userId, 0);
            
            Map<String, Object> response = new HashMap<>();
            response.put("history", history);
            response.put("total", history.size());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("❌ 查询试衣历史失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 删除试衣历史
     */
    @DeleteMapping("/history/{id}")
    public ResponseEntity<Map<String, Object>> deleteHistory(@PathVariable Long id) {
        log.info("========== 删除试衣历史 ==========");
        log.info("历史ID: {}", id);
        
        try {
            TryonHistory history = tryonHistoryRepository.findById(id).orElse(null);
            if (history == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("message", "历史记录不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            history.setIsDeleted(1);
            tryonHistoryRepository.save(history);
            
            Map<String, Object> response = new HashMap<>();
            response.put("message", "删除成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("❌ 删除试衣历史失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("message", "删除失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 删除服装
     */
    @DeleteMapping("/garments/{id}")
    public ResponseEntity<Map<String, Object>> deleteGarment(@PathVariable Long id) {
        log.info("========== 删除服装 ==========");
        log.info("服装ID: {}", id);
        
        try {
            GarmentLibrary garment = garmentLibraryRepository.findById(id).orElse(null);
            if (garment == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("message", "服装不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            garment.setIsDeleted(1);
            garmentLibraryRepository.save(garment);
            
            Map<String, Object> response = new HashMap<>();
            response.put("message", "删除成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("❌ 删除服装失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("message", "删除失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 更新服装信息
     */
    @PutMapping("/garments/{id}")
    public ResponseEntity<Map<String, Object>> updateGarment(
            @PathVariable Long id,
            @RequestBody GarmentUpdateRequest request) {
        log.info("========== 更新服装信息 ==========");
        log.info("服装ID: {}", id);
        
        try {
            GarmentLibrary garment = garmentLibraryRepository.findById(id).orElse(null);
            if (garment == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("message", "服装不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            if (request.getGarmentName() != null) {
                garment.setGarmentName(request.getGarmentName());
            }
            if (request.getGarmentType() != null) {
                garment.setGarmentType(request.getGarmentType());
            }
            if (request.getRemarks() != null) {
                garment.setRemarks(request.getRemarks());
            }
            if (request.getColor() != null) {
                garment.setColor(request.getColor());
            }
            if (request.getBrand() != null) {
                garment.setBrand(request.getBrand());
            }
            
            garmentLibraryRepository.save(garment);
            
            Map<String, Object> response = new HashMap<>();
            response.put("message", "更新成功");
            response.put("garment", garment);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("❌ 更新服装失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("message", "更新失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 查询用户的形象库
     */
    @GetMapping("/persons")
    public ResponseEntity<Map<String, Object>> getUserPersons(@RequestParam("userId") Long userId) {
        log.info("========== 查询用户形象库 ==========");
        log.info("用户ID: {}", userId);
        
        try {
            List<PersonLibrary> persons = personLibraryRepository.findByUserIdAndIsDeletedOrderByIsDefaultDescCreatedAtDesc(userId, 0);
            
            Map<String, Object> response = new HashMap<>();
            response.put("persons", persons);
            response.put("total", persons.size());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("❌ 查询形象库失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 删除形象
     */
    @DeleteMapping("/persons/{id}")
    public ResponseEntity<Map<String, Object>> deletePerson(@PathVariable Long id) {
        log.info("========== 删除形象 ==========");
        log.info("形象ID: {}", id);
        
        try {
            PersonLibrary person = personLibraryRepository.findById(id).orElse(null);
            if (person == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("message", "形象不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            person.setIsDeleted(1);
            personLibraryRepository.save(person);
            
            Map<String, Object> response = new HashMap<>();
            response.put("message", "删除成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("❌ 删除形象失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("message", "删除失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 设置默认形象
     */
    @PutMapping("/persons/{id}/default")
    public ResponseEntity<Map<String, Object>> setDefaultPerson(
            @PathVariable Long id,
            @RequestParam("userId") Long userId) {
        log.info("========== 设置默认形象 ==========");
        log.info("形象ID: {}, 用户ID: {}", id, userId);
        
        try {
            // 取消当前默认
            personLibraryRepository.findByUserIdAndIsDefaultAndIsDeleted(userId, 1, 0)
                .ifPresent(person -> {
                    person.setIsDefault(0);
                    personLibraryRepository.save(person);
                });
            
            // 设置新默认
            PersonLibrary person = personLibraryRepository.findById(id).orElse(null);
            if (person == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("message", "形象不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            person.setIsDefault(1);
            personLibraryRepository.save(person);
            
            Map<String, Object> response = new HashMap<>();
            response.put("message", "设置成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("❌ 设置默认形象失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("message", "设置失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 更新形象信息
     */
    @PutMapping("/persons/{id}")
    public ResponseEntity<Map<String, Object>> updatePerson(
            @PathVariable Long id,
            @RequestBody PersonUpdateRequest request) {
        log.info("========== 更新形象信息 ==========");
        log.info("形象ID: {}", id);
        
        try {
            PersonLibrary person = personLibraryRepository.findById(id).orElse(null);
            if (person == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("message", "形象不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            if (request.getPersonName() != null) {
                person.setPersonName(request.getPersonName());
            }
            if (request.getRemarks() != null) {
                person.setRemarks(request.getRemarks());
            }
            
            personLibraryRepository.save(person);
            
            Map<String, Object> response = new HashMap<>();
            response.put("message", "更新成功");
            response.put("person", person);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("❌ 更新形象失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("message", "更新失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    @Data
    public static class TryOnRequest {
        private String personImageUrl;
        private List<GarmentItem> garments;  // 服装列表（支持多件）
        private Long userId;  // 用户ID
        
        // 向后兼容：如果前端还发送旧格式
        private String garmentImageUrl;
        private Long garmentId;
        private String garmentType;
        private String garmentName;
    }
    
    @Data
    public static class GarmentItem {
        private String imageUrl;
        private String type;
        private String name;
        private Long garmentId;
    }
    
    @Data
    public static class SaveHistoryRequest {
        private Long userId;
        private String personImageUrl;
        private Long garmentId;
        private String garmentImageUrl;
        private String resultImageUrl;
        private String garmentType;
    }
    
    @Data
    public static class GarmentUpdateRequest {
        private String garmentName;
        private String garmentType;
        private String remarks;
        private String color;
        private String brand;
    }
    
    @Data
    public static class PersonUpdateRequest {
        private String personName;
        private String remarks;
    }
}

